#stable release:
#OSG_URL = "http://www.openscenegraph.org/downloads/stable_releases/OpenSceneGraph-%(VERSION)s/source/OpenSceneGraph-%(VERSION)s.zip"
#developers release:
#"http://www.openscenegraph.org/downloads/developer_releases/OpenSceneGraph-%(VERSION)s.zip"
#def urldecider(machine, dirs, version):

DEVELOPERS_OSG_URL = "http://www.openscenegraph.org/downloads/developer_releases/OpenSceneGraph-%(VERSION)s.zip"
STABLE_OSG_URL = "http://www.openscenegraph.org/downloads/stable_releases/OpenSceneGraph-%(SHORTVERSION)s/source/OpenSceneGraph-%(VERSION)s.zip"
                  

DEFAULT_VERSION = "3.2.1"
VERSIONS = ["2.8.3", "2.9.7", "2.9.8","2.9.9", "2.9.10", "2.9.11", "2.9.12", "2.9.13", "2.9.14", "2.9.15", "3.0.0", "3.0.1", "3.1.3", "3.2.0", "3.2.1"]
DEPENDS = ["zlib", "ilmbase", "openexr", "jpeg", "png", "tiff", "gif", "freetype", "collada_dom", "qt4osmin"]

def urldecider( machine, dirs, version):
  if version in ("2.8.3", "3.0.0", "3.0.1"):
    shortversion = "3.0" if version == "3.0.0" else version
    return STABLE_OSG_URL % {"SHORTVERSION" : shortversion, "VERSION" : version}
  else:
    return DEVELOPERS_OSG_URL % {"VERSION" : version}

URL = urldecider

#note:
#( version 2.9.8 or greater requires additional empty parameter "" for the find dependency)

from source.builders import *
import os, shutil

class OsgCMakeBuilder( CMakeBuilder ):

  def getOrCreate3rdParty(self):
    """Collect bin lib and include folders of seperate libs to create a third party dir for osg """

    #get the directories of the 3rd party libs from the other modules
    thirdPartyDir = self.directories.build+os.sep+"3rdparty"

    collectdirs = [self.dependencies[extdir].targetpath() for extdir in ["zlib","jpeg","png","tiff","gif","freetype"]]

    #copy the files in include and lib dirs
    Collector(collectdirs, thirdPartyDir, removeandcreatedir = True ) 
     
    #OpenSceneGraph currently searches for the libungif version, so we rename the static libs
    #we could also update the search module (submission)  
    if self.machine.isWindows():
      shutil.copy( thirdPartyDir+os.sep+"lib"+os.sep+"giflib.lib", thirdPartyDir+os.sep+"lib"+os.sep+"libungif.lib" )
      shutil.copy( thirdPartyDir+os.sep+"lib"+os.sep+"giflibd.lib", thirdPartyDir+os.sep+"lib"+os.sep+"libungifD.lib" )
    
  def configure( self ):

    self.getOrCreate3rdParty()
    
    #this is needed in 2.9.8
    if self.version == "2.9.8":
      replacement = ( ".*QT4_WRAP_CPP", "QT4_WRAP_CPP( SOURCES_H_MOC ${SOURCES_H} OPTIONS \"-f\" )")
      self.replaceLinesInFile( self.extractedpath+"\\src\\osgQt\\CMakeLists.txt", [replacement] )

    #we want NOTIFY_DISABLED for the final release
    #todo add an option to build/install a release version with notify on (for developers)
    notifydisabled = "" if self.debug else " -DOSG_NOTIFY_DISABLED=TRUE"

    if self.machine.isWindows():
      self.osgenv = os.environ

      #add qt (mainly for examples to build as reference material)  
      self.osgenv['QTDIR'] = self.dependencies['qt4osmin'].targetpath()
      
      #add collada
      print( "collada-dom build directies need to be available for collada-dom to be found correctly" )
      print( self.directories.build+"\\collada_dom\\dom" )
      self.osgenv['COLLADA_DIR'] = self.directories.build+"\\collada-dom"
      #boost filesystem and system are copied by the collada-dom builder into the dom external-libs dir

      #add our freetype version
      freetype_dir = self.dependencies["freetype"].targetpath().replace("\\", "/")
      self.osgenv['FREETYPE_DIR'] = freetype_dir
      
      replacements = [( "^  NAMES", "  NAMES "+freetype_dir+"/lib" ),
       ( ".*\\$ENV\\{FREETYPE_DIR\\}/include/freetype2", "$ENV{FREETYPE_DIR}/include/freetype2 $ENV{FREETYPE_DIR}/include" )]
      self.replaceLinesInFile( self.extractedpath+"/CMakeModules/FindFreeType.cmake", replacements )
      
      replacement_freetype = ( ".*FREETYPE ft2build.h", "FIND_DEPENDENCY(FREETYPE ft2build.h \"freetype;freetype2311MT;freetype234;freetype234MT;freetype235;freetype237;freetype238;freetype244\" ${OSG_3RDPARTY_BIN} \"_D\" \"\")" )
      #self.replaceLinesInFile( self.extractedpath+"/CMakeModules/Find3rdPartyDependencies.cmake", [replacement] )     

      #add our png version, ( version 2.9.8 or greater requires additional empty parameter "" )
      #osg 2.9.8:
      replacement_png = ""
      if self.version in ["2.8.3", "2.9.7"]:
        replacement_png = ( ".*PNG png.h", "FIND_DEPENDENCY(PNG png.h \"libpng;libpng13;png14;libpng14\" ${OSG_3RDPARTY_BIN} \"D\")" )
      else:
        replacement_png = ( ".*PNG png.h", "FIND_DEPENDENCY(PNG png.h \"libpng;libpng13;png14;libpng14\" ${OSG_3RDPARTY_BIN} \"D\" \"\")" )
      
      self.replaceLinesInFile( self.extractedpath+"/CMakeModules/Find3rdPartyDependencies.cmake", [replacement_freetype, replacement_png] )     

      self.replaceLinesInFile( self.extractedpath+"/applications/osgviewer/osgviewer.cpp", [("#include <stdint.h>", "//#include <stdint.h>")] )
      

      #pass zlib dir to the command line
      zlibdep = self.dependencies["zlib"]
      incdir = " -DZLIB_INCLUDE_DIR="+zlibdep.getincludedir()
      lib = " -DZLIB_LIBRARY="+zlibdep.getlibdir()+"\\zlib.lib "
      manifeston = " -DOSG_MSVC_GENERATE_PLUGINS_AND_WRAPPERS_MANIFESTS=ON "

      #provide the paths to ILM libs and includes
      #add openexr
      openexrdep = self.dependencies['openexr']
      ilmbasedep = self.dependencies['ilmbase']

      openexr_defines = " -DOPENEXR_INCLUDE_DIR="+openexrdep.getincludedir()+\
                        " -DOPENEXR_Half_LIBRARY="+ilmbasedep.getlibdir()+"/Half.lib"+\
                        " -DOPENEXR_Iex_LIBRARY="+ilmbasedep.getlibdir()+"/Iex-2_1.lib"+\
                        " -DOPENEXR_IlmIlf_LIBRARY="+openexrdep.getlibdir()+"/IlmImf-2_1.lib"+\
                        " -DOPENEXR_IlmThread_LIBRARY="+ilmbasedep.getlibdir()+"/IlmThread-2_1.lib "

      CMakeBuilder.configure(self, incdir+lib+notifydisabled+manifeston+openexr_defines)

    else:
      import build_freetype, build_ffmpeg
      self.osgenv = os.environ

      self.osgenv['QTDIR'] = self.dependencies['qt4osmin'].targetpath()
      self.osgenv['COLLADA_DIR'] = self.directories.build+os.sep+"collada-dom"
      self.osgenv['FREETYPE_DIR'] = self.dependencies["freetype"].targetpath()

      #currenlty ffmpeg is not in the depends list
      #ffmpeg_dir = build_ffmpeg.getffmpegdir(self.machine, self.directories)
      #self.osgenv['FFMPEG_DIR'] = ffmpeg_dir      

      incdir = " -DCMAKE_INCLUDE_PATH="+self.directories.build+os.sep+"3rdparty"+os.sep+"include"
      libdir = " -DCMAKE_LIBRARY_PATH="+self.directories.build+os.sep+"3rdparty"+os.sep+"lib"
      CMakeBuilder.configure( self, incdir+libdir+notifydisabled )
  def make_devenv(self):
    self.call_devenv("OpenSceneGraph.sln", "INSTALL.vcproj")

BUILDER = OsgCMakeBuilder
